/**
 * 图标缓存管理器
 * 实现智能缓存策略，包括LRU算法和持久化存储
 */

class IconCache {
  constructor(maxSize = 500, persistKey = 'icon-cache') {
    this.maxSize = maxSize
    this.persistKey = persistKey
    this.cache = new Map()
    this.accessTime = new Map()
    this.loadFromStorage()
  }

  /**
   * 从本地存储加载缓存
   */
  loadFromStorage() {
    try {
      const stored = localStorage.getItem(this.persistKey)
      if (stored) {
        const data = JSON.parse(stored)
        // 只加载最近的缓存项
        const recent = Object.entries(data).slice(-this.maxSize / 2)
        recent.forEach(([key, value]) => {
          this.cache.set(key, value)
          this.accessTime.set(key, Date.now())
        })
      }
    } catch (error) {
      console.warn('Failed to load cache from storage:', error)
    }
  }

  /**
   * 保存缓存到本地存储
   */
  saveToStorage() {
    try {
      const data = Object.fromEntries(this.cache)
      localStorage.setItem(this.persistKey, JSON.stringify(data))
    } catch (error) {
      console.warn('Failed to save cache to storage:', error)
    }
  }

  /**
   * 获取缓存项
   */
  get(key) {
    if (this.cache.has(key)) {
      // 更新访问时间
      this.accessTime.set(key, Date.now())
      return this.cache.get(key)
    }
    return null
  }

  /**
   * 设置缓存项
   */
  set(key, value) {
    // 如果缓存已满，清理最久未访问的项
    if (this.cache.size >= this.maxSize) {
      this.evictLRU()
    }

    this.cache.set(key, value)
    this.accessTime.set(key, Date.now())

    // 定期持久化（每50次操作）
    if (this.cache.size % 50 === 0) {
      this.saveToStorage()
    }
  }

  /**
   * 检查是否存在
   */
  has(key) {
    return this.cache.has(key)
  }

  /**
   * 删除缓存项
   */
  delete(key) {
    this.cache.delete(key)
    this.accessTime.delete(key)
  }

  /**
   * 清空缓存
   */
  clear() {
    this.cache.clear()
    this.accessTime.clear()
    localStorage.removeItem(this.persistKey)
  }

  /**
   * LRU淘汰策略
   */
  evictLRU() {
    let oldestKey = null
    let oldestTime = Date.now()

    for (const [key, time] of this.accessTime) {
      if (time < oldestTime) {
        oldestTime = time
        oldestKey = key
      }
    }

    if (oldestKey) {
      this.delete(oldestKey)
    }
  }

  /**
   * 获取缓存统计信息
   */
  getStats() {
    return {
      size: this.cache.size,
      maxSize: this.maxSize,
      usage: Math.round((this.cache.size / this.maxSize) * 100)
    }
  }

  /**
   * 预热缓存 - 批量设置
   */
  warmup(entries) {
    entries.forEach(([key, value]) => {
      this.set(key, value)
    })
  }
}

/**
 * SVG处理缓存 - 专门用于缓存处理后的SVG内容
 */
class SVGProcessCache extends IconCache {
  constructor() {
    super(1000, 'svg-process-cache')
  }

  /**
   * 生成基于样式设置的缓存键
   */
  generateKey(iconName, settings) {
    const settingsHash = this.hashSettings(settings)
    return `${iconName}_${settingsHash}`
  }

  /**
   * 简单的设置哈希函数
   */
  hashSettings(settings) {
    return btoa(JSON.stringify(settings)).slice(0, 8)
  }
}

/**
 * 元数据缓存 - 用于缓存图标元数据
 */
class MetadataCache extends IconCache {
  constructor() {
    super(100, 'metadata-cache')
  }

  /**
   * 获取或设置图标元数据
   */
  getOrSet(key, factory) {
    let value = this.get(key)
    if (value === null) {
      value = factory()
      this.set(key, value)
    }
    return value
  }
}

// 导出缓存实例
export const svgProcessCache = new SVGProcessCache()
export const metadataCache = new MetadataCache()
export { IconCache }

// 默认导出基础缓存类
export default IconCache
